<template>
  <el-card class="mb-6">
    <template #header>
      <div class="flex justify-between items-center" style="display: flex; justify-content: space-between;">
        <h2 class="font-bold">轮播图管理</h2>
        <el-button type="primary" @click="openAddModal" style="flex:  right;">
          <el-icon><Plus /></el-icon> 添加轮播图
        </el-button>
      </div>
    </template>
    
    <el-row class="mb-4">
      <!-- <el-col :span="12">
        <el-input v-model="searchQuery" placeholder="搜索标题/描述" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </el-col>
      <el-col :span="6">
        <el-select v-model="statusFilter" placeholder="筛选状态">
          <el-option label="全部状态" value="all" />
          <el-option label="已启用" value="active" />
          <el-option label="已禁用" value="inactive" />
        </el-select>
      </el-col> -->
      <el-col :span="6" class="text-right">
        <el-button type="primary" @click="fetchCarousels">
          <el-icon><Refresh /></el-icon> 刷新数据
        </el-button>
      </el-col>
    </el-row>
    
    <el-table
      :data="filteredSlides"
      border
      stripe
      highlight-current-row

      v-loading="loading"
      element-loading-text="加载中..."
    >


      <el-table-column label="图片" width="250" >
        <template #default="scope" >
          <div style="padding: 5px;">
          <el-image :src="scope.row.imageUrl" style="height: 150px; width: 215px;" :preview-src-list="[scope.row.imageUrl]" class="w-16 h-16 object-cover rounded" />

          </div>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="150" />
      <!-- <el-table-column prop="description" label="描述" min-width="200">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <div class="text-ellipsis overflow-hidden" style="max-width: 200px">{{ scope.row.description || '-' }}</div>
          </el-tooltip>
        </template>
      </el-table-column> -->
      <el-table-column prop="sort" label="排序" width="200">
        <template #default="scope">
          <el-input-number 
            v-model.number="scope.row.sort" 
            size="small" 
            @change="handleSortChange(scope.row, $event)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button-group>
            <el-button size="mini" type="primary" @click.stop="editSlide(scope.row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="mini" type="danger" @click.stop="deleteSlide(scope.row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    

  </el-card>
  
  <!-- 预览区域 -->
  <!-- <el-card>
    <template #header>
      <h3 class="font-bold">前台预览</h3>
    </template>
    
    <el-carousel height="300px" arrow="always" indicator-position="outside" :autoplay="previewAutoPlay">
      <el-carousel-item v-for="(item) in activeSlides" :key="item.id">
        <div class="relative h-full">
          <el-image :src="item.imageUrl" class="w-full h-full object-cover" fit="cover" />
          <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-4">
            <h4 class="text-white font-semibold text-lg">{{ item.title || '轮播图' }}</h4>
            <p class="text-white/80 text-sm">{{ item.description || '' }}</p>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>
  </el-card> -->
  
  <!-- 编辑对话框 -->
  <el-dialog 
    v-model="dialogVisible" 
    :title=editingSlide
    width="50%"
    :before-close="handleClose"
  >


      <el-form :model="formData" label-width="100px" ref="formRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <!-- <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入描述（可选）" />
        </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model.number="formData.sort" :min="0" placeholder="请输入排序值" />
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <!-- <el-input v-model="formData.imageUrl" placeholder="请输入图片URL" /> -->

            <el-upload class="avatar-uploader" action="/travel/products/upload" :show-file-list="false"
                :on-success="handleAvatarSuccessMain" :before-upload="beforeAvatarUpload" :headers="uploadHeaders">
                <img v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>

        </el-form-item>

        <!-- <el-form-item label="图片预览">
          <el-image v-if="formData.imageUrl" :src="formData.imageUrl" class="w-full h-40 object-contain border rounded" fit="contain" />
          <div v-else class="w-full h-40 border rounded flex items-center justify-center text-gray-400">无预览图</div>
        </el-form-item> -->
      </el-form>


      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSlide">保存</el-button>
      </span>

  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { 
  Plus, Search, Edit, Delete, Check, Close, 
  ArrowUp, ArrowDown, Refresh
} from '@element-plus/icons-vue';
import { 
  getCarouselList, 
  addCarousel, 
  delCarouselById, 
  updateCarouselById 
} from '../../api/settings';
import { ElMessage, ElMessageBox } from 'element-plus';

import { useLoginEmpStore } from '../../stores/loginEmp';

// 状态管理
const loading = ref(false);
const error = ref(null);

// 轮播图数据
const slides = ref([]);


const handleAvatarSuccess = (response, uploadFile, index) => {
  // 通过索引找到对应的景点元素，设置其attractionImage属性
  formData.imageUrl = response.data;
};
const handleAvatarSuccessMain = (response, uploadFile, index) => {
  // 通过索引找到对应的景点元素，设置其attractionImage属性
  formData.imageUrl = response.data;
};
//文件上传前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('文件格式不正确')
    return false //不执行上传操作
  }
  return true
}
const loginEmpStore = useLoginEmpStore();
// 从 store 中获取 token 并计算请求头
const uploadHeaders = computed(() => {
  const loginEmp = loginEmpStore.getLoginEmp();
  return loginEmp && loginEmp.token
    ? { 'authorization': loginEmp.token }
    : {};
});


// 搜索和过滤
const searchQuery = ref('');
const statusFilter = ref('all');
const filteredSlides = computed(() => {
  return slides.value
    .filter(slide => {
      if (statusFilter.value === 'all') return true;
      // 假设 sort > 0 为启用状态，否则为禁用
      return statusFilter.value === 'active' ? parseInt(slide.sort) > 0 : parseInt(slide.sort) <= 0;
    })
    .filter(slide => {
      if (!searchQuery.value) return true;
      const query = searchQuery.value.toLowerCase();
      return slide.title.toLowerCase().includes(query) || 
             (slide.description || '').toLowerCase().includes(query);
    })
    .sort((a, b) => parseInt(a.sort) - parseInt(b.sort));
});

// 选择状态
const selectedSlides = ref([]);

// 对话框状态
const dialogVisible = ref(false);
const editingSlide = ref("");
const formData = reactive({
  id:null,
  imageUrl: '',
  title: '',
  sort: 0
});
const formRef = ref(null);

// 预览区域
const activeSlides = computed(() => 
  slides.value
    .filter(slide => parseInt(slide.sort) > 0)
    .sort((a, b) => parseInt(a.sort) - parseInt(b.sort))
);
const previewAutoPlay = computed(() => activeSlides.value.length > 1);

// 生命周期钩子
onMounted(() => {
  fetchCarousels();
});

// 获取轮播图列表
const fetchCarousels = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    const response = await getCarouselList();
    slides.value = response.data || [];
    ElMessage.success('数据加载成功');
  } catch (err) {
    error.value = err.message || '获取轮播图列表失败';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 打开添加对话框
const openAddModal = () => {
  editingSlide.value = "添加轮播图";
  formData.imageUrl = '';
  formData.title = '';
  formData.sort = slides.value.length > 0 ? parseInt(slides.value[slides.value.length - 1].sort) + 1 : 1;
  dialogVisible.value = true;
};

// 编辑轮播图
const editSlide = (slide) => {
  editingSlide.value = "编辑轮播图";
  formData.id = slide.id;
  formData.imageUrl = slide.imageUrl;
  formData.title = slide.title;
  formData.sort = parseInt(slide.sort);
  dialogVisible.value = true;
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
};

// 保存轮播图
const saveSlide = async () => {
  // 简单表单验证
  if (!formData.imageUrl) {
    ElMessage.error('请输入图片URL');
    return;
  }
  
  if (!formData.title) {
    ElMessage.error('请输入标题');
    return;
  }
  
  try {
    if (formData.id) {
      // 更新现有轮播图

      const updatedData = {
        id: formData.id,
        imageUrl: formData.imageUrl,
        title: formData.title,
        sort: formData.sort.toString()
      };
      
      await updateCarouselById(formData.id, updatedData);
      const index = slides.value.findIndex(item => item.id === formData.id);
      if (index !== -1) {
        slides.value[index] = { ...slides.value[index], ...updatedData };
        sortSlidesBySortField();
      }
      
      ElMessage.success('轮播图更新成功');
    } else {
      // 添加新轮播图
      const newData = {
        imageUrl: formData.imageUrl,
        title: formData.title,
        sort: formData.sort.toString()
      };
      
      const response = await addCarousel(newData);
      if (response.id) {
        slides.value.push({ ...newData, id: response.id });
        sortSlidesBySortField();
      } else {
        // 服务器没有返回ID，使用本地生成的临时ID
        slides.value.push({ ...newData, id: Date.now() });
        sortSlidesBySortField();
      }
      
      ElMessage.success('轮播图添加成功');
    }
    
    dialogVisible.value = false;
  } catch (err) {
    error.value = err.message || '保存轮播图失败';
    ElMessage.error(error.value);
  }
};

// 删除轮播图
const deleteSlide = async (slide) => {
  ElMessageBox.confirm(
    `确定要删除轮播图 "${slide.title}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      console.log(slide.id);
      
      await delCarouselById(slide.id);
      const index = slides.value.findIndex(item => item.id === slide.id);
      
      if (index !== -1) {
        slides.value.splice(index, 1);
        sortSlidesBySortField();
        ElMessage.success('轮播图删除成功');
      }
    } catch (err) {
      error.value = err.message || '删除轮播图失败';
      ElMessage.error(error.value);
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 批量删除
// const deleteSelected = async () => {
//   if (selectedSlides.value.length === 0) {
//     ElMessage.warning('请先选择轮播图');
//     return;
//   }
  
//   ElMessageBox.confirm(
//     `确定要删除选中的 ${selectedSlides.value.length} 个轮播图吗？`,
//     '提示',
//     {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning'
//     }
//   ).then(async () => {
//     try {
//       // 串行删除，避免并发问题
//       for (const slide of selectedSlides.value) {
//         await delCarouselById(slide.id);
//       }
      
//       slides.value = slides.value.filter(slide => 
//         !selectedSlides.value.some(selected => selected.id === slide.id)
//       );
      
//       selectedSlides.value = [];
//       sortSlidesBySortField();
//       ElMessage.success('已删除选中的轮播图');
//     } catch (err) {
//       error.value = err.message || '删除轮播图失败';
//       ElMessage.error(error.value);
//     }
//   }).catch(() => {
//     // 用户取消操作
//   });
// };




// 处理排序变更
const handleSortChange = async (slide, newSort) => {
  try {
    await updateCarouselById(slide.id, { sort: newSort.toString() });
    sortSlidesBySortField();
    // ElMessage.success('排序更新成功');
  } catch (err) {
    // 回滚本地更改
    slide.sort = parseInt(slide.sort);
    error.value = err.message || '更新排序失败';
    ElMessage.error(error.value);
  }
};

// 按sort字段排序轮播图
const sortSlidesBySortField = () => {
  slides.value.sort((a, b) => parseInt(a.sort) - parseInt(b.sort));
};

// 行点击事件
const handleRowClick = (row) => {
  editSlide(row);
};
</script>  
<style>
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border: 1px dashed;
}

</style>